package base.cmd;
import java.io.BufferedReader;
import java.io.FileReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class LinuxInfo
{
	//list of storing cpu information
	private static ArrayList< Map<String, String>> cpuList;
	private static Map<String, String> memList;
	/**
	 * initialize all information
	 * */
	private static void init()throws Exception
	{
		cpuList = new ArrayList<Map<String,String>>();
		memList = new HashMap<String, String>();
	}
	
	/**
	 * return a map object
	 * */
	private static Map<String, String> getMap()throws Exception
	{
		return new HashMap<String, String>();
	}
	
	/**
	 * get all linux information
	 * */
	private static void getLinuxInfo()throws Exception
	{
		BufferedReader br = new BufferedReader(new FileReader("/proc/cpuinfo"));
		String line;
		
		Map<String, String> cpu = null;//new cpu
		
		while((line = br.readLine())!=null)
		{
			//System.out.println(line);
			String[] data = line.split(":");
			if(data.length > 1)
			{
				if(data[0].trim().equalsIgnoreCase("processor"))
				{
					if(cpu != null)
					{
						cpuList.add(cpu);//add a new cpu
					}
					cpu = getMap();//get a new map object
					
					cpu.put(data[0].trim(), data[1].trim());
					
				}
				else 
				{
					cpu.put(data[0].trim(), data[1].trim());
				}
			}
		}
		cpuList.add(cpu);
		br.close();
		
		br = new BufferedReader(new FileReader("/proc/meminfo"));
		while((line = br.readLine())!=null)
		{
			String[] data = line.split(":");
			if (data.length > 1)
			{
				memList.put(data[0].trim(), data[1].trim());
			}
		}
		br.close();
	}
	
	/**
	 * check system
	 * */
	private static void checkSystem()throws Exception
	{
		if (!System.getProperty("os.name").equalsIgnoreCase("linux"))
		{
			throw new Exception("您的系统不是Linux，无法操作！");
		}
	}
	/**
	 * 获取CPU Model的名称
	 * */
	public static String getModelName()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return cpuList.get(0).get("model name");
	}
	
	/**
	 * 获取CPU Model的名称
	 * @param processorCount -- 标识的第几个逻辑CPU
	 * */
	public static String getModelName(int processorCount)throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		if(processorCount > cpuList.size())
			throw new Exception("您计算机上没有那么多逻辑CPU，请调整processorCount大小。");
		return cpuList.get(processorCount-1).get("model name");
	}
	
	/**
	 * 获取CPU处理器的编号
	 * @param processorCount -- 标识的第几个逻辑CPU
	 * */
	public static String getProcessor(int processorCount)throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		if(processorCount > cpuList.size())
			throw new Exception("您计算机上没有那么多逻辑CPU，请调整processorCount大小。");
		return cpuList.get(processorCount-1).get("processor");
	}
	
	/**
	 * 获取CPU的主频
	 * */
	public static String getCpuMHz()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return cpuList.get(0).get("cpu MHz");
	}
	
	/**
	 * 获取CPU的主频
	 * @param processorCount -- 标识的第几个逻辑CPU
	 * */
	public static String getCpuMHz(int processorCount)throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		if(processorCount > cpuList.size())
			throw new Exception("您计算机上没有那么多C逻辑CPU，请调整processorCount大小。");
		return cpuList.get(processorCount-1).get("cpu MHz");
	}
	
	/**
	 * bogomips是Linux操作系统中衡量计算机处理器运行速度的一种尺度
	 * */
	public static String getBogoMips()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return cpuList.get(0).get("bogomips");
	}
	
	/**
	 * bogomips是Linux操作系统中衡量计算机处理器运行速度的一种尺度
	 * @param processorCount -- 标识的第几个逻辑CPU
	 * */
	public static String getBogoMips(int processorCount)throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		if(processorCount > cpuList.size())
			throw new Exception("您计算机上没有那么多逻辑CPU，请调整processorCount大小。");
		return cpuList.get(processorCount-1).get("bogomips");
	}
	
	/**
	 * 获取CPU的cache的大小
	 * */
	public static String getCacheSize()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return cpuList.get(0).get("cache size");
	}
	
	/**
	 * 获取CPU的cache的大小
	 * @param processorCount -- 标识的第几个逻辑CPU
	 * */
	public static String getCacheSize(int processorCount)throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		if(processorCount > cpuList.size())
			throw new Exception("您计算机上没有那么多逻辑CPU，请调整processorCount大小。");
		return cpuList.get(processorCount-1).get("cache size");
	}
	
	/**
	 * 获取CPU的位数（32 or 64）
	 * */
	public static int getCPUBits()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		if (cpuList.get(0).get("flags").contains(" lm "))
		{
			return 64;
		}
		else 
		{
			return 32;
		}
	}
	
	/**
	 * 获取处理器的名字或厂商
	 * */
	public static String getProcessorName()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return cpuList.get(0).get("vendor id");
	}
	/**
	 * 获取CPU的核的数量
	 * */
	public static String getCores()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return cpuList.get(0).get("cpu cores");
	}
	
	/**
	 * 获取逻辑CPU的数量
	 * */
	public static int getThreadNumber()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return cpuList.size();
	}
	
	/**
	 * 列出所有逻辑CPU的信息
	 * */
	public static void listAllCPU()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		for (int i = 0; i < cpuList.size(); i++)
		{
			for (Iterator cpu = cpuList.get(i).keySet().iterator();cpu.hasNext();)
			{
				String name = (String)cpu.next();
				String value = cpuList.get(i).get(name);
				System.out.println(name+"\t"+value);
			}
			System.out.println();
		}
	}
	
	/**
	 * 获取内存的大小
	 * */
	public static String getMemSize()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return memList.get("MemTotal");
	}
	
	/**
	 * 获取当前内存的空闲大小
	 * */
	public static String getMemFreeSize()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return memList.get("MemFree");
	}
	
	/**
	 * 获取用来给文件做缓冲的缓冲区大小
	 * */
	public static String getBufferSize()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return memList.get("Buffers");
	}
	
	/**
	 * 获取被高速缓冲器使用掉的内存
	 * */
	public static String getCachedSize()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return memList.get("Cached");
	}
	
	/**
	 * 获取已被高速缓冲器使用的交换空间大小
	 * */
	public static String getSwapCachedSize()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return memList.get("SwapCached");
	}
	
	/**
	 * 获取在活跃使用中的缓冲或高速缓冲存储器页面文件的大小，除非非常必要否则不会被移作他用.
	 * */
	public static String getActiveSize()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return memList.get("Active");
	}
	
	/**
	 * 获取在不经常使用中的缓冲或高速缓冲存储器页面文件的大小，可能被用于其他途径.
	 * */
	public static String getInActiveSize()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return memList.get("Inactive");
	}
	
	/**
	 * 获取交换空间的总大小
	 * */
	public static String getSwapSize()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return memList.get("SwapTotal");
	}
	
	/**
	 * 获取未被使用交换空间大小
	 * */
	public static String getSwapFreeSize()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return memList.get("SwapFree");
	}
	
	/**
	 * 获取等待被写回磁盘的内存大小
	 * */
	public static String getDirtySize()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return memList.get("Dirty");
	}
	
	/**
	 * 获取正在被写回磁盘的内存大小
	 * */
	public static String getWriteBackSize()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		return memList.get("WriteBack");
	}
	
	/**
	 * 获取所有内存使用情况
	 * */
	public static void listAllMem()throws Exception
	{
		checkSystem();
		init();
		getLinuxInfo();
		for (Iterator cpu = memList.keySet().iterator();cpu.hasNext();)
		{
			String name = (String)cpu.next();
			String value = memList.get(name);
			System.out.println(name+"\t"+value);
		}
	}
	
	/**
	 * 获取操作系统的名称
	 * */
	public static String getSystemName()throws Exception
	{
		return System.getProperty("os.name");
	}
	
	/**
	 * 获取操作系统的架构
	 * */
	public static String getSystemArch()throws Exception
	{
		return System.getProperty("os.arch");
	}
	
	/**
	 * 获取操作系统的版本
	 * */
	public static String getSystemVersion()throws Exception
	{
		return System.getProperty("os.version");
	}
	
	/**
	 * 获取系统用户的名称
	 * */
	public static String getUserName()throws Exception
	{
		return System.getProperty("user.name");
	}
	
	/**
	 * 获取本机IP
	 * */
	public static String getLocalIP()throws Exception
	{
		String sip = null;
		InetAddress ip = null;  
		boolean bFindIP = false;
		Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces();
		while (netInterfaces.hasMoreElements()) 
		{
			if(bFindIP)
			{
				break;
		    }
		    NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
		    //----------特定情况，可以考虑用ni.getName判断
		    //遍历所有ip
		    Enumeration<InetAddress> ips = ni.getInetAddresses();
		    while (ips.hasMoreElements()) 
		    {
		    	ip = (InetAddress) ips.nextElement();
		    	if( ip.isSiteLocalAddress()&& !ip.isLoopbackAddress()   //127.开头的都是lookback地址
		                 && ip.getHostAddress().indexOf(":")==-1)
		    	{
		    		bFindIP = true;
		            break;   
		        } 
		     }
		}
		if (ip != null)
		{
			sip = ip.getHostAddress();
		}
		return sip;
	}
	public static void main(String[] args)throws Exception
	{
		System.out.println("该方法暂时没用！");
	}
}
